﻿using Grow.Domain.Repository.CreateDomainRepository;
using Grow.Domain.Repository.EntityFrameworkCore.CreateDomainRepository;
using Grow.Module.Builder;
using Grow.Module.Service;
using Microsoft.EntityFrameworkCore;

namespace Grow.Domain.Repository.EntityFrameworkCore.SqlServer
{
    public class SqlServerDbContext : DbContextBase
    {
        private readonly ICreateDomainRepositoryBuilder _createRepositoryBuilder;

        public SqlServerDbContext(DbContextOptions options, IServiceContext serviceContext) : base(options, serviceContext)
        {
            IBuilderManager builderManager = serviceContext.GetRequiredService<IBuilderManager>();
            _createRepositoryBuilder = builderManager.GetRequiredBuilder<ICreateDomainRepositoryBuilder>();
        }

        #region OnModelCreating(配置映射)
        /// <summary>
        /// 配置映射
        /// </summary>
        /// <param name="modelBuilder">映射生成器</param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            IEnumerable<IDbMap> tableMaps = _createRepositoryBuilder.GetTableMaps();
            DbBuilder dbBuilder = new(modelBuilder);
            foreach (IDbMap tableMap in tableMaps)
            {
                tableMap.AddDb(dbBuilder);
            }
        }
        #endregion
    }
}
